package com.tr.syn;

/**
 * @author TRasdzz
 * @since  2021/3/11 11:44
 * @version  version-1.0
 */
//不安全的买票
//线程不安全的
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"小红").start();
        new Thread(buyTicket,"小绿").start();
        new Thread(buyTicket,"黄牛").start();
    }
}

class BuyTicket implements Runnable {

    //票
    private int ticketNums = 10;
    //外部停止方法
    boolean flag = true;

    @Override
    public void run() {
        //买票
        while (flag){
            try {
                Thread.sleep(100);
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //synchronized 同步方法，锁的是this
    private synchronized void buy() {
        //判断是否还有余票
        if (ticketNums <= 0){
            flag = false;
            return;
        }


        //输出买票人和买了第几张票
        System.out.println(Thread.currentThread().getName() + "买了第" + ticketNums-- +
                "张票");
    }
}
//小红买了第10张票
//小绿买了第9张票
//黄牛买了第8张票
//小红买了第7张票
//黄牛买了第6张票
//小绿买了第5张票
//小绿买了第4张票
//小红买了第3张票
//黄牛买了第2张票
//小绿买了第1张票